package com.csw.android.androidtest.net.socket.udp;

public class Packet {

    /**
     * 每包数据的包头
     * index        length(byte)        mean
     * 0            1                   message id (0x00~0xFF循环)
     * 1            1                   packet flag (1 最后一包数据,0 非最后一包数据)
     * 2            2                   data length (message 数据长度)
     */
    public static final int headBytesLength = 4;


    public static Packet parsePacket(byte[] packetData) {
        if (packetData.length < 4) {
            return null;
        }
        byte id = packetData[0];
        int flag = 0xFF & packetData[1];
        int dataLength = (0xFF & packetData[2] << 8) | (0xFF & packetData[3]);
        byte[] pd = new byte[packetData.length - 4];
        System.arraycopy(packetData, 4, pd, 0, pd.length);
        return new Packet(id, flag, dataLength, pd);
    }

    private final byte messageId;
    private final int isLast;
    private final int messageDataLength;
    private final byte[] data;

    public Packet(byte messageId, int isLast, int messageDataLength, byte[] data) {
        this.messageId = messageId;
        this.isLast = isLast;
        this.messageDataLength = messageDataLength;
        this.data = data;
    }

    public byte getMessageId() {
        return messageId;
    }

    public int getIsLast() {
        return isLast;
    }

    public int getMessageDataLength() {
        return messageDataLength;
    }

    public byte[] getData() {
        return data;
    }

    public byte[] getDataWithHeader() {
        byte[] headerData = new byte[data.length + 4];
        headerData[0] = messageId;
        headerData[1] = (byte) isLast;
        headerData[2] = (byte) (messageDataLength & 0xFF00 >> 8);
        headerData[3] = (byte) (messageDataLength & 0xFF);
        System.arraycopy(data,0,headerData,4,data.length);
        return headerData;
    }
}
